package com.gexiaobao.pigeon.ui.breeding_pigeon

import android.annotation.SuppressLint
import android.graphics.BitmapFactory
import android.os.Bundle
import android.widget.ImageView
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import com.flyjingfish.openimagelib.OpenImage
import com.flyjingfish.openimagelib.enums.MediaType
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.model.bean.BreedingPigeonDetailResponse
import com.gexiaobao.pigeon.app.model.bean.EditBloodInfoBean
import com.gexiaobao.pigeon.app.model.bean.ImageListBean
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.util.WxShareUtils
import com.gexiaobao.pigeon.databinding.ActivityBloodPigeonInfoBinding
import com.gexiaobao.pigeon.ui.adapter.AdapterBloodPigeonPicture
import com.gexiaobao.pigeon.ui.dialog.RxDialogDefault
import com.gexiaobao.pigeon.ui.view.recycleview.FullyGridLayoutManager
import com.gexiaobao.pigeon.viewmodel.BreedingPigeonViewModel
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.LogUtils
import me.hgj.jetpackmvvm.util.startActivity

/**
 * @Author      : hxw
 * @Date        : 2024/9/10 10:04
 * @Describe    : 种鸽信息
 */
class ActivityBloodPigeonInfo : BaseActivity<BreedingPigeonViewModel, ActivityBloodPigeonInfoBinding>() {

    private val mListImage: MutableList<ImageListBean> = arrayListOf()
    private var mPigeonId = 0
    private val mAdapter: AdapterBloodPigeonPicture by lazy { AdapterBloodPigeonPicture(arrayListOf()) }
    private lateinit var mDataBean: BreedingPigeonDetailResponse
    private var mShareUrl = ""
    private var mRingId = ""
    private var mRingIdYear = ""
    private var mRingIdArea = ""
    private var mGradesDesc = ""
    private var mSex = ""
    private var mCoverImage = ""
    private var mCoverImageUrl = ""
    private var isAmend = false
    private lateinit var editBloodInfo: EditBloodInfoBean

    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setTranslucentForImageView(this, 0, null)
        mDatabind.includeBar.tvTitle.text = getString(R.string.base_info)
        mDatabind.includeBar.tvRightMenu.text = getString(R.string.Breeding_management)
        mDatabind.includeBar.tvRightMenu.isVisible = true
        isAmend = intent.getBooleanExtra("isAmend", false)
        mDatabind.includeBar.tvRightMenu.isVisible = isAmend
        mPigeonId = intent.getIntExtra("pigeonId", 0)
        onRefresh()

        mDatabind.swipeRefreshLayout.init {
            onRefresh()
        }
        val manager = FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false)
        mDatabind.recyclerView.init(manager, mAdapter)

        mAdapter.setOnItemClickListener { _, _, position ->
            openAdapterBigImage(position, mListImage)
        }

        eventViewModel.toRefreshData.observeInActivity(this) {
            onRefresh()
        }
    }

    private fun openAdapterBigImage(position: Int, data: MutableList<ImageListBean>) {
        val listImage = arrayListOf<String>()
        if (data.isNotEmpty()) {
            data.forEach {
                listImage.add(it.url)
            }
        }
        OpenImage.with(this)
            .setClickRecyclerView(mDatabind.recyclerView) { _, _ -> R.id.ivItemBloodPigeonPic }
            /** 点击的ImageView的ScaleType类型（如果设置不对，打开的动画效果将是错误的） */
            .setSrcImageViewScaleType(ImageView.ScaleType.CENTER_CROP, true)
            .setImageUrlList(listImage, MediaType.IMAGE)
            .setClickPosition(position)
            .show()
    }

    private fun onRefresh() {
        showLoading(getString(R.string.loading))
        mViewModel.getBreedingPigeonInfo(mPigeonId.toString())
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun createObserver() {
        super.createObserver()
        /** 删除种鸽信息 */
        mViewModel.deletePigeonResult.observe(this) {
            if (it.isSuccess) {
                eventViewModel.toRefreshData.value = true
                finish()
            } else {
                showMessage(it.errorMsg)
            }
        }
        /** 获取种鸽详情 */
        mViewModel.detailResult.observe(this) {
            if (mDatabind.swipeRefreshLayout.isRefreshing) {
                mDatabind.swipeRefreshLayout.isRefreshing = false
            }
            mDataBean = it
            mDatabind.data = it
            mSex = it.sex
            mShareUrl = it.shareUrl
            mRingId = it.ringId
            mRingIdYear = it.year
            mRingIdArea = it.area
            mGradesDesc = it.gradesDesc
            mDatabind.isVisible = it.category == "公棚"
            mListImage.clear()
            mListImage.addAll(it.list)
            mAdapter.setList(mListImage)
            mAdapter.notifyDataSetChanged()
            val ringId = it.year + "-" + if (it.area.isEmpty()) "00" else it.area + "-" + it.ringId
            editBloodInfo = EditBloodInfoBean(
                country = it.country,
                countryEn = it.countryEn,
                eye = it.eye,
                featherColor = it.featherColor,
                gradesDesc = it.gradesDesc,
                level = 1,
                levelInfo = "1",
                name = it.name,
                ringId = ringId,
                sex = it.sex,
                title = getString(R.string.Chief_pigeon),
            )
            val photoFlag = it.photoFlag
            if (mListImage.isNotEmpty() && photoFlag != 0) {
                mListImage.forEachIndexed { index, imageListBean ->
                    if (photoFlag - 1 == index) {
                        mCoverImage = imageListBean.path
                        mCoverImageUrl = imageListBean.url
                    }
                }
            }
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.btnShare,
            mDatabind.btnModify,
            mDatabind.btnDelete,
            mDatabind.tvBloodBook,
            mDatabind.includeBar.ivBack,
            mDatabind.includeBar.tvRightMenu
        ) {
            when (it) {
                mDatabind.includeBar.tvRightMenu -> startActivity<ActivityBreedingManagement>(
                    "pigeonId" to mPigeonId,
                    "intentType" to "blood",
                    "sex" to mSex
                )

                mDatabind.includeBar.ivBack -> finish()
                mDatabind.tvBloodBook -> startActivity<ActivityMakeBlood>(
                    "type" to "blood",
                    "pigeonId" to mPigeonId,
                    "editBloodInfo" to editBloodInfo,
                    "imagePath" to mCoverImage,
                    "imageUrl" to mCoverImageUrl
                )

                mDatabind.btnShare -> shareBaseInfoToWeChat()
                mDatabind.btnModify -> startActivity<ActivityAddBloodPigeon>("id" to mPigeonId, "type" to 2, "isAmend" to isAmend)
                mDatabind.btnDelete -> showDefaultDialog()
            }
        }
    }

    private fun shareBaseInfoToWeChat() {
        val ringId = mRingIdYear + "-" + if (mRingIdArea.isEmpty()) "00" else "$mRingIdArea-$mRingId"
        try {
            val bmp = BitmapFactory.decodeResource(resources, R.mipmap.app_icon_)
            WxShareUtils.shareWeb(this, Constant.WX_APP_ID, mShareUrl, ringId, mGradesDesc, bmp)
        } catch (e: Exception) {
            e.printStackTrace()
            LogUtils.warnInfo("种鸽信息分享失败")
        }
    }

    private fun showDefaultDialog() {
        val dialog = RxDialogDefault(this)
        dialog.setTitle(getString(R.string.are_you_sure_delete_pigeon))
        dialog.setSureListener {
            showLoading(getString(R.string.loading))
            mViewModel.delBreedingPigeonInfo(mPigeonId.toString())
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }
}